package com.reservation.repository;

import com.reservation.entity.Reservation;
import com.reservation.enums.ReservationStatus;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 预定数据访问接口
 */
@Repository
public interface ReservationRepository extends JpaRepository<Reservation, Long> {

    /**
     * 根据用户ID查找预定记录
     */
    List<Reservation> findByUserIdOrderByCreatedAtDesc(Long userId);

    /**
     * 根据用户ID和状态查找预定记录
     */
    List<Reservation> findByUserIdAndStatusOrderByCreatedAtDesc(Long userId, ReservationStatus status);

    /**
     * 根据商品ID查找预定记录
     */
    List<Reservation> findByProductIdOrderByCreatedAtDesc(Long productId);

    /**
     * 根据状态查找预定记录
     */
    List<Reservation> findByStatusOrderByCreatedAtDesc(ReservationStatus status);

    /**
     * 统计用户的预定数量
     */
    @Query("SELECT COUNT(r) FROM Reservation r WHERE r.userId = :userId")
    Long countByUserId(@Param("userId") Long userId);

    /**
     * 统计指定状态的预定数量
     */
    Long countByStatus(ReservationStatus status);

    /**
     * 统计用户指定状态的预定数量
     */
    Long countByUserIdAndStatus(Long userId, ReservationStatus status);

    /**
     * 查找指定时间范围内的预定记录
     */
    @Query("SELECT r FROM Reservation r WHERE r.createdAt BETWEEN :startTime AND :endTime ORDER BY r.createdAt DESC")
    List<Reservation> findByCreatedAtBetween(@Param("startTime") LocalDateTime startTime, 
                                           @Param("endTime") LocalDateTime endTime);

    /**
     * 查找超时未确认的预定记录
     */
    @Query("SELECT r FROM Reservation r WHERE r.status = 'PENDING' AND r.createdAt < :expireTime")
    List<Reservation> findExpiredPendingReservations(@Param("expireTime") LocalDateTime expireTime);

    /**
     * 根据联系电话查找预定记录
     */
    List<Reservation> findByContactPhoneOrderByCreatedAtDesc(String contactPhone);
}
